﻿using System;
using System.Web;
using System.Web.Security;
using Sharp.WeShare.Common;
using Sharp.WeShare.MP.JSSDK.Entity;

namespace Sharp.WeShare.MP.JSSDK
{
    public class JsApi
    {
        /// <summary>
        /// 获取jssdk签名
        /// </summary>
        /// <param name="noncestr">随机字符串</param>
        /// <param name="jsapi_ticket">ticket</param>
        /// <param name="timestamp">时间戳</param>
        /// <param name="url">当前网页的URL</param>
        /// <returns></returns>
        public static string GetSign(string noncestr, string jsapi_ticket, int timestamp, string url)
        {
            //将字段添加到列表中
            string[] arr = new[]
            {
                string.Format("noncestr={0}",noncestr),
                string.Format("jsapi_ticket={0}",jsapi_ticket),
                string.Format("timestamp={0}",timestamp),
                string.Format("url={0}",url)
             };
            //字典排序
            Array.Sort(arr);
            //使用URL键值对的格式拼接成字符串
            var temp = string.Join("&", arr);
            return FormsAuthentication.HashPasswordForStoringInConfigFile(temp,
            "SHA1");
        }

        /// <summary>
        /// 获取config接口注入时的参数
        /// </summary>
        /// <param name="appId">微信公众号唯一标识</param>
        /// <param name="accessToken">接口调用凭证</param>
        /// <param name="debug">是否开启调试模式</param>
        /// <returns></returns>
        public static WxJsParam GetConfig(string appId,string accessToken, bool debug=false)
        {
            var req = HttpContext.Current.Request;

            var param = new WxJsParam
            {
                appId = appId,
                debug = debug,
                nonceStr = Utils.GetTimeStamp().ToString(),
                timestamp = Utils.GetTimeStamp(),
                url = req.Url.Scheme,
            };
            var ticket = JsApiTicket.GetValue(appId, accessToken);
            param.signature = GetSign(param.nonceStr, ticket, param.timestamp, param.url);
            return param;
        }
    }
}